package com.tools.bitbucket.controller;

import com.alibaba.fastjson.JSON;
import com.tools.bitbucket.config.BitbucketConfig;
import com.tools.bitbucket.pojo.AjaxResult;
import com.tools.bitbucket.pojo.BackUpRequest;
import com.tools.bitbucket.pojo.BitbucketProject;
import com.tools.bitbucket.service.BackUpAsyncService;
import com.tools.bitbucket.utils.FileUtils;
import com.tools.bitbucket.utils.HttpUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.mail.internet.InternetAddress;
import java.io.File;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Future;

@RestController
@Slf4j
public class BitbucketController {
    //"http://{bitbucketUrl}/rest/api/1.0/projects?limit=1000";
    private static final String REPOSITORY_URL = "http://%s/rest/api/1.0/projects?limit=1000";
    //"http://{bitbucketUrl}/rest/api/1.0/projects/{repositoryName}/repos?limit=1000";
    private static final String PROJECT_URL = "http://%s/rest/api/1.0/projects/%s/repos?limit=1000";
    //存放项目历史备份信息
    public List<BitbucketProject> bitbucketProjectJsonList = new ArrayList<>();
    //存放服务器获取的项目信息
    public List<BitbucketProject> bitbucketProjectBitbucketList = new ArrayList<>();
    //存放异步备份代码操作的执行结果
    private List<Future<Boolean>> futureList = new ArrayList<>();
    @Autowired
    private BitbucketConfig bitbucketConfig;
    @Autowired
    private JavaMailSenderImpl javaMailSender;
    @Value("${spring.mail.nickname}")
    private String fromMailUserNickname;
    @Autowired
    private BackUpAsyncService backUpAsyncService;

    @PostMapping("/backUp")
    public AjaxResult backUp(@RequestBody BackUpRequest backUpRequest) {
        //初始化
        bitbucketProjectJsonList = new ArrayList<>();
        bitbucketProjectBitbucketList = new ArrayList<>();
        futureList = new ArrayList<>();

        // 参数校验
        if (StringUtils.isEmpty(bitbucketConfig.getBackUpPath()) || !FileUtils.directoryExists(bitbucketConfig.getBackUpPath())) {
            return AjaxResult.error("备份路径 不存在!");
        }
        if (StringUtils.isEmpty(bitbucketConfig.getBaseUrl())) {
            return AjaxResult.error("bitbucket server base url 不能为空!");
        }
        if (StringUtils.isEmpty(bitbucketConfig.getAdminToken())) {
            return AjaxResult.error("管理员访问凭证 不能为空!");
        }
        if (null != backUpRequest.getToMailList() && backUpRequest.getToMailList().size() > 0) {
            if (StringUtils.isEmpty(javaMailSender.getUsername())) {
                return AjaxResult.error("邮件发起人 不能为空!");
            }
            if (StringUtils.isEmpty(javaMailSender.getPassword())) {
                return AjaxResult.error("邮件发送凭证 不能为空!");
            }
        }

        //组装历史备份版本信息
        File latestVersionInfo = new File(bitbucketConfig.getBackUpPath() + File.separator + "latestVersionInfo.json");
        if (latestVersionInfo.exists()) {
            bitbucketProjectJsonList = JSON.parseArray(FileUtils.readFileByLines(latestVersionInfo), BitbucketProject.class);
        }

        //获取所有仓库
        HttpUtils.ADMIN_TOKEN = bitbucketConfig.getAdminToken();
        String strResult = HttpUtils.sendGet(String.format(REPOSITORY_URL, bitbucketConfig.getBaseUrl()));
        List<BitbucketProject> bitbucketProjectList = JSON.parseArray(JSON.parseObject(strResult).get("values").toString(), BitbucketProject.class);
        if (null != bitbucketProjectList && bitbucketProjectList.size() > 0) {
            //将服务器项目信息存放至列表
            bitbucketProjectList.stream().forEach(repository -> {
                BitbucketProject bitbucketProject = new BitbucketProject();
                //此处需要重新创建对象进行存储，防止与bitbucketRepositoryJsonList操作同一对象，相互影响
                BeanUtils.copyProperties(repository, bitbucketProject);
                bitbucketProjectBitbucketList.add(bitbucketProject);
            });
            bitbucketProjectList.stream().forEach(
                    bitbucketProject -> {
                        //启动线程，对项目进行备份，并将执行结果组装至futureList
                        futureList.add(backUpAsyncService.getRepository(bitbucketProject, bitbucketProjectJsonList, bitbucketProjectBitbucketList));
                    }
            );
        }

        try {
            //发送邮件
            //组装发件人信息
            InternetAddress fromMail = new InternetAddress();
            fromMail.setAddress(javaMailSender.getUsername());
            fromMail.setPersonal(fromMailUserNickname);
            //异步发送邮件
            backUpAsyncService.sendMail(futureList, bitbucketProjectJsonList, bitbucketProjectBitbucketList, latestVersionInfo, fromMail, backUpRequest.getToMailList());
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return AjaxResult.success();
    }


}
